package mobile.pubcrawler;

import java.util.ArrayList;

import mobile.pubcrawler.model.DataModel;
import mobile.pubcrawler.model.DataModelLocation;
import mobile.pubcrawler.ui.NextPub;
import mobile.pubcrawler.ui.SearchPub;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;

public class MyListAdapter extends BaseAdapter {
    /**
     * Remember our context so we can use it when constructing views.
     */
    private Context mContext;
    private DataModel dml;
    private static Filter filter;
    //private int currentView;
    private int mode;//searchPub mode or nextPub mode
    private int screen_width;
    private int pubsSelected = 0;
	
	public MyListAdapter(Context context, int _mode){
		mContext = context;
		mode= _mode;

		loadLocations();
    	
    	DisplayMetrics displaymetrics = new DisplayMetrics();
		((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);  
		screen_width = displaymetrics.widthPixels;
	
	}
	
	public void loadLocations() {
		
		dml = DataModel.getInstance();
		dml.setLocationList(new ArrayList<DataModelLocation>());
		
		pubsSelected = 0;
		if (mode==0) ((SearchPub)mContext).setPubsSelected(pubsSelected);
		
		filter = Filter.getInstance();
		DataModel.getInstance().setStartAddress(filter.getRelativeToAddress());
		LocalSearch search = new LocalSearch(filter);
    	search.execute(this);
    	
	}
	
	public void setDataModel(ArrayList<DataModelLocation> locations, int progress, boolean complete) {
		dml.setLocationList(locations);
		if (mode==1) {
			((NextPub)mContext).setProgressBar(progress);
			if (complete) {
				((NextPub)mContext).setHeadline(mContext.getString(R.string.nextPubHeadline));
				((NextPub)mContext).hideProgressBar();
				if (dml.getLocationList().size()==0) ((NextPub)mContext).showNoLocationMessage();			
			}
		}
		if (mode==0) {
			((SearchPub)mContext).setProgressBar(progress);
			if (complete) {
				((SearchPub)mContext).setHeadline(mContext.getString(R.string.searchPubHeadline));
				((SearchPub)mContext).hideProgressBar();
				if (dml.getLocationList().size()==0) ((SearchPub)mContext).showNoLocationMessage();
			}
		}
		this.notifyDataSetChanged();
	}
	
	public int getCount(){
		return dml.getLocationList().size();
	}
	
    public Object getItem(int position) {
        return position;
    }
    
    public long getItemId(int position) {
        return position;
    }
	
    public View getView(int position, View convertView, ViewGroup parent) {
    	LocationEntry le = new LocationEntry(mContext, dml.getLocationList().get(position), position, mode);
        return le.getView();
    }
    
    private class LocationEntry {
        
    	private View view;
    	private ImageButton selectButton;
    	private final int searchPub_notAvailableWidth = 115;
    	private final int nextPub_notAvailableWidth = 125;
    	
    	public LocationEntry(Context context, DataModelLocation location, int position, int mode) {
        	
        	final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        	view = inflater.inflate(R.layout.locationlistitem, null);         	

        	TextView description = (TextView)view.findViewById(R.id.description); 
            description.setText(Html.fromHtml(location.getName()));
            description.setTextSize(14);
                    
            TextView address = (TextView)view.findViewById(R.id.address); 
            address.setText(Html.fromHtml(location.getAddress()+"<br>"+location.getPostalCode()+" "+location.getCity()));
            address.setTextSize(12);
            
            TextView distance = (TextView)view.findViewById(R.id.distance); 
            distance.setText(String.valueOf(location.getDistance())+"m");
            distance.setTextSize(12);
            
            view.setOnClickListener(new detailsListener(position));

            RatingBar rating = (RatingBar)view.findViewById(R.id.small_ratingbar); 
            rating.setNumStars(5);
            rating.setIsIndicator(true);
            rating.setRating(location.getOverallRating());
           
            ImageButton logo = (ImageButton)view.findViewById(R.id.logo); 
            logo.setImageResource(PubCrawlerUI.getInstance().getImageResource(location.getCategory()));
            logo.setOnClickListener(new detailsListener(position));
            
            selectButton = (ImageButton)view.findViewById(R.id.selectButton); 
            
            if(mode==0) {
            	description.setWidth(screen_width-searchPub_notAvailableWidth);
            	address.setWidth(screen_width-searchPub_notAvailableWidth);
            	setPlusMinusIcon(dml.getLocationList().get(position).isSelected(), position, false);
            	selectButton.setBackgroundDrawable(null);
            	selectButton.setOnClickListener(new selectOrDeselectListener(position));
            }else if(mode == 1) {
            	description.setWidth(screen_width-nextPub_notAvailableWidth);
            	address.setWidth(screen_width-nextPub_notAvailableWidth);
            	selectButton.setImageResource(R.drawable.map);
            	selectButton.setBackgroundDrawable(null);
            	selectButton.setOnClickListener(new routePubListener(position));
            }
            
        }
        
        public View getView() {
        	return view;
        }
        
        public class detailsListener implements OnClickListener {
        	int position;
        	public detailsListener(int pos){
        		position = pos;
        	}
            public void onClick(View v) {
            	PubCrawlerUI.getInstance().startPubDetails(position);
            }
        }
        public class routePubListener implements OnClickListener {
        	int position;
        	public routePubListener(int pos){
        		position = pos;
        	}
            public void onClick(View v) {
            	for(DataModelLocation dl : dml.getLocationList()){
            		dl.setSelected(false);
            	}
            	dml.getLocationList().get(position).setSelected(true);
            	PubCrawlerUI.getInstance().startCurrentPubUI(position);
            }
        }
        public class selectOrDeselectListener implements OnClickListener {
        	int position;
        	public selectOrDeselectListener(int pos){
        		position = pos;
        	}
            public void onClick(View v) {
                setPlusMinusIcon(!dml.getLocationList().get(position).isSelected(), position, true);
                ((SearchPub)mContext).setPubsSelected(pubsSelected);
            }
        }
        private void setPlusMinusIcon(boolean selected, int position, boolean updateStatus) {
        	if (updateStatus) dml.getLocationList().get(position).setSelected(selected);
        	if (selected) {
        		selectButton.setImageResource(R.drawable.minusicon_40x40);
        		view.setBackgroundColor(Color.argb(100, 0, 140, 0));
        		if (updateStatus) pubsSelected++;
            } else {
            	selectButton.setImageResource(R.drawable.plusicon_40x40);
            	if (updateStatus) {
            		pubsSelected--;
            		view.setBackgroundColor((int)Long.parseLong("FF191919", 16));
            	}
            }
        }
    }

}
